package com.ruoyi.third.sms;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.ICallBack;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;

import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.third.config.ThirdConfig;
import com.ruoyi.third.domain.SmsHis;
import com.ruoyi.third.service.ISmsHisService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 发送短信工具类
 *
 * @author wujiyue
 */
//用户登录名称 sms@1836570483042872.onaliyun.com
//AccessKey ID LTAI5tAiZWVYH2TMUoz8oSMS
//AccessKey Secret GjltOAzyNXMoF5X1Jl3HM0sZjarses
@Slf4j
@Component
public class SmsUtil {
    protected static Logger logger = LoggerFactory.getLogger(SmsUtil.class);

    private static String leYunAccount = ThirdConfig.getSmsLeYunAccount();

    private static String leYunPassword = ThirdConfig.getSmsLeYunPassword();
    @Autowired
    private ISmsHisService smsHisService;
    static ISmsHisService ssmsHisService;

    @PostConstruct
    public void init() {
        SmsUtil.ssmsHisService = this.smsHisService;
    }

    /**
     * 乐云短信
     *
     * @param phone   发送的号码
     * @param content 发送短信内容
     * @param prefix  内容前缀该字符串会被“【】”包裹并添加到content最前面
     * @return
     */
    public static AjaxResult sendLeYunSms(String phone, String prefix, String content) {
        try {
            if (StringUtils.isNotEmpty(prefix)) {
                prefix = "【" + prefix + "】";
                content = prefix + content;
            }
            content = java.net.URLEncoder.encode(content, "UTF-8");// 用UTF-8编码执行URLEncode
            String _url = "http://www.lehuo520.cn/a/sms/api/send"; //接口地址
            String _param = "username=" + leYunAccount + "&password=" + leYunPassword + "&phone=" + phone + "&content=" + content + "&type=1";
            URL url = null;
            HttpURLConnection urlConn = null;
            url = new URL(_url);
            urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestMethod("POST");
            urlConn.setDoOutput(true);
            OutputStream out = urlConn.getOutputStream();
            out.write(_param.getBytes("UTF-8"));
            out.flush();
            out.close();
            BufferedReader rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
            StringBuffer sb = new StringBuffer();
            int ch;
            while ((ch = rd.read()) > -1) {
                sb.append((char) ch);
            }
            System.out.println(sb);
            //{"result":"-1","describing":"帐号不存在，请检查用户名或者密码是否正确","sms":[]}
            rd.close();
            JSONObject jsonObject = JSON.parseObject(sb.toString());
            int code = jsonObject.getIntValue("result");
            String msg = jsonObject.getString("describing");
            if (code == 0) {
                return AjaxResult.success(msg);
            } else {
                return AjaxResult.error(msg);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return AjaxResult.error(ex.getMessage());
        }

    }

    /**
     * 乐云短信
     *
     * @param phone    发送的号码
     * @param content  发送短信内容
     * @param callBack 回调函数，传入该接口的一个实现类并定义成功和失败后执行的方法
     * @return
     */
    public static AjaxResult sendLeYunSms(String phone, String prefix, String content, ICallBack callBack) {
        AjaxResult res = sendLeYunSms(phone, prefix, content);
        if (res.isSuccess()) {
            callBack.onSuccess();
        } else {
            callBack.onFail();
        }
        return res;
    }

    /**
     * 阿里短信
     *
     * @param phone   发送的号码
     * @param content 发送短信内容
     * @return
     */
    public static boolean sendAliRegisterSms(String phone, String content) {
        com.aliyun.dysmsapi20170525.Client client = null;
        try {
            client = createClient("LTAI5tAiZWVYH2TMUoz8oSMS", "GjltOAzyNXMoF5X1Jl3HM0sZjarses");
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setTemplateCode("SMS_211760571")
                    .setSignName("西北升学")
                    .setTemplateParam("{\"code\":\"" + content + "\"}");
            // 复制代码运行请自行打印 API 的返回值

            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            log.info("短信发生结果：" + sendSmsResponse.getBody().message);
            SmsHis smsHis = new SmsHis();
            smsHis.setPhone(phone);
            smsHis.setCarrieroperator("阿里短信");
            smsHis.setContent(content);
            smsHis.setReturncode(sendSmsResponse.getBody().code);
            smsHis.setReturnContent(sendSmsResponse.getBody().message);
            ssmsHisService.insertSmsHis(smsHis);
            if ("OK".equals(sendSmsResponse.getBody().code)) {
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    public static void main(String[] args_) throws Exception {
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dysmsapi20170525.Client client = createClient("LTAI5tAiZWVYH2TMUoz8oSMS", "GjltOAzyNXMoF5X1Jl3HM0sZjarses");
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers("15706049886")
                .setTemplateCode("SMS_211760571")
                .setSignName("学途教育")
                .setTemplateParam("{\"code\":\"123456\"}");
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
        System.out.println(sendSmsResponse.getBody().message);
    }
}
